<template>
  <Page :show-nav-bar="false" v-slot:default="{contentClass}">
    <div :class="contentClass" class="bg-gray-100 overflow-scroll" style="padding-top: 0; height: 100vh;">

      <LoadingBox v-if="pageLoading" class="w-40 h-40 absolute mt-8" style="z-index: 1; left: calc((100% - 10rem)/2)">
        <span>加载中...</span>
      </LoadingBox>

      <template v-else>
        <div class="rounded-sm absolute w-full" style="background: linear-gradient(0deg, #ffffff 0, #fa8c16); z-index: 0; height: 10rem;"></div>
        <div class="h-2"></div>
        <div class="relative bg-white m-auto rounded flex flex-col items-center py-3" style=" z-index: 1; width: 97%">
          <div class="font-bold text-sm less-title"><span>解锁剩余时间</span></div>
          <van-count-down  class="text-white text-xs mt-2" :time="downtime" millisecond>
            <template #default="timeData">
              <span class="text-white bg-orange-100 text-orange-500 font-bold p-1">{{ spaceNumber(timeData.hours) }} : {{ spaceNumber(timeData.minutes) }} : {{ spaceNumber(timeData.seconds) }} : {{ spaceNumber(parseInt(timeData.milliseconds/10)) }}</span>
            </template>
          </van-count-down>

          <template v-if="activity.commision_config.coupon_bonus">
            <div class="flex mt-5 px-1">
              <van-image :src="invite1"></van-image>
              <van-image :src="invite2"></van-image>
              <van-image :src="invite3"></van-image>
            </div>

            <div class="w-full px-3">
              <van-steps :active="couponProcess.write_off_count-1" active-icon="success" active-color="#38f">
                <van-step v-for="(el, index) in activity.commision_config.coupon_bonus_settings">
                  <div v-if="(index+1) > couponProcess.write_off_count">差1人返现{{el.money}}元</div>
                  <div v-else>已获得返现金额{{el.money}}元</div>
                </van-step>
              </van-steps>
            </div>
            <van-button v-show="downtime>0" round style="background: linear-gradient(90deg,#fa541c 0,#fa8c16); margin-top: .5rem;" class="w-4/5" @click="onPoster"><span class="text-white text-lg">赚{{maxBonus}}元返现</span></van-button>
          </template>

<!--          <div class="text-center text-sm p-4">-->
<!--            <p>解锁全部内容需要邀请 {{taskTotal}}人</p>-->
<!--            <p>当前已邀请 {{touchUser.share_count}} 人，多多分享加快解锁礼包~</p>-->
<!--          </div>-->
<!--          <div class="flex gap-3">-->
<!--            <div v-for="i in 4" class="flex flex-col items-center">-->
<!--              <div class="text-xs text-orange-500">待领取</div>-->
<!--              <van-image :src="bag" class="w-12"></van-image>-->
<!--              <div class="-mt-4 text-xs text-white bg-orange-600 rounded-lg text-center relative index-1 w-full">&yen;{{activity.commision_config.money}}元</div>-->
<!--            </div>-->
<!--            <div class="border p-2 text-xs w-12 h-12 text-center mt-4 border-orange-300 bg-orange-100 text-orange-500" style="border-radius: 50%;" @click="onAll">-->
<!--              查看<br>-->
<!--              全部-->
<!--            </div>-->
<!--          </div>-->
<!--          <van-button v-show="downtime>0" round style="background: linear-gradient(90deg,#fa541c 0,#fa8c16); margin-top: 1.5rem;" class="w-4/5" @click="onPoster"><span class="text-white text-lg">邀请好友{{activity.goods.discount_price}}元助力</span></van-button>-->
        </div>

        <div class=" bg-white m-auto rounded flex flex-col items-center py-3 mt-2" style="width: 97%">
          <van-tabs v-model:active="active" class="w-full" color="#fa8c16" title-active-color="#fa8c16">
            <van-tab title="全部权益"></van-tab>
            <van-tab title="我的权益"></van-tab>
          </van-tabs>

          <div>
            <template v-for="el in [...rights.pay, ...rights.assistance]">
              <div class="flex mt-3" v-if="active==0 || el.unlock">
                <van-image :src="el.cover.url" style="width: 6rem; height: 6rem;" round radius="5"></van-image>
                <div class="ml-3 border-box relative" style="width: 13.6875rem;">
                  <div class="font-bold text-gray-500 text-sm truncate w-full">{{el.name}}</div>
                  <div class="text-xs mt-1">{{el.description}}</div>
                  <div v-if="el.unlock_config.condition_type=='buy_once'" class="w-full absolute bottom-2 flex justify-between"><!--购买立得-->
                    <div>
                      <div class="bottom-2 text-xs text-gray-400">购买解锁</div>
                      <div class="bottom-2 text-xs mt-1" v-if="!el.unlock" :class="{'text-orange-500': true}">未解锁</div>
                      <div class="bottom-2 text-xs mt-1" v-else :class="{'text-green-500': true}">已解锁</div>
                    </div>
                    <div>
                      <template v-if="el.unlock">
                        <template v-if="el.unlock_config.unlocked_dispatch_coupon"><!--卡券权益-->
                          <van-button class="border border-green-200" plain round size="small" style="border: 1px solid rgb(34 197 94)" @click="onCoupon(el)">
                            <span class="text-sm text-green-500">查看卡券</span>
                          </van-button>
                        </template>
                        <van-button v-else class="border border-green-200" plain round size="small" style="border: 1px solid rgb(34 197 94)" @click="onCode(el)">
                          <span class="text-sm text-green-500">查看权益</span>
                        </van-button>
                      </template>
                      <van-button v-else class="border" plain round size="small" style="border: 1px solid rgb(34 197 94)">
                        <span class="text-sm text-green-500">去购买</span>
                      </van-button>
                    </div>
                  </div>
                  <div v-else class="w-full absolute bottom-2 flex justify-between"><!--分享助力-->
                    <div>
                      <div class="bottom-2 text-xs text-gray-400">累计邀请{{el.unlock_config.count}}人解锁</div>
                      <div class="bottom-2 text-xs text-orange-500 mt-1">当前已邀请{{touchUser ? touchUser.share_count: '--'}}人</div>
                    </div>
                    <div>
                      <van-button v-if="el.unlock" class="border border-green-200" plain round size="small" style="border: 1px solid rgb(34 197 94)" @click="onCode(el)">
                        <span class="text-sm text-green-500">查看权益</span>
                      </van-button>
                      <van-button v-else class="border" plain round size="small" style="border: 1px solid rgb(249 115 22)" @click="onPoster">
                        <span class="text-sm text-orange-500">免费领取</span>
                      </van-button>
                    </div>
                  </div>
                </div>
              </div>
            </template>

          </div>

        </div>

        <div style="height: 4rem" class="bottom-safe"></div>
        <div class="fixed bg-white w-full bottom-0 shadow flex justify-between items-center px-2" style="height: 3.125rem">
          <div class="flex items-center flex-1">
            <div class="flex flex-col justify-center px-3">
              <van-icon name="wap-home-o"  color="#fa541c" size="1.5rem"/>
              <div class="text-xs w-full" style="color:#fa541c;" @click="onHome">首页</div>
            </div>
            <div class="flex flex-col justify-center px-3">
              <van-icon name="service-o" class="text-gray-500" size="1.5rem"/>
              <div class="text-xs w-full text-gray-500" @click="showService=true">客服</div>
            </div>
          </div>
          <div class="w-4/5 flex justify-end">
            <van-button round style="background-color: rgb(250, 140, 22); border-top-right-radius: initial; border-bottom-right-radius: initial; border-right: initial;" @click="onRank">
              <div class="text-white">
                我的收益
              </div>
            </van-button>
            <template v-if="downtime>0">
              <van-button round style="background: linear-gradient(90deg,#fa541c 0,#fa8c16); border-top-left-radius: initial; border-bottom-left-radius: initial; border-left: initial;" @click="onPoster">
                <div class="text-white">
                  赚{{maxBonus}}元返现
                </div>
              </van-button>
            </template>
            <template v-else>
              <van-button round style="background: linear-gradient(90deg,#fa541c 0,#fa8c16); border-top-left-radius: initial; border-bottom-left-radius: initial; border-left: initial;" @click="showService=true">
                <div class="text-white">
                  活动已结束
                </div>
              </van-button>
            </template>
          </div>
        </div>

        <van-popup v-model:show="showCode"
                   closeable
                   position="bottom"
                   :style="{ height: '60%' }"
                   class="rounded-lg">
          <div class="relative">
            <div class="text-center border-b" style="line-height: 3.5rem;">我的核销码</div>
            <div class="text-center text-red-600 font-bold pt-4">
              <p>向工作人员出示”二维码“</p>
              <p>此码仅可使用一次，请勿泄漏</p>
            </div>
            <div class="flex justify-center">
              <canvas class="qrcode" ref="qrcode"></canvas>
            </div>
          </div>
        </van-popup>

        <van-popup v-model:show="showService" class="relative rounded-lg w-3/5" style="overflow-y: initial">
          <div class="w-full">
            <div class="p-3 border-b text-center">植得客服</div>
            <div class="p-3">
              <div class="text-red-600 flex justify-between text-sm items-center">
                <div>
                  <van-icon name="phone" size="1rem"/>
                  <span class="ml-2">{{activity.activity.extra.service_contact}}</span>
                </div>
                <van-button size="small" color="#ff0000" :url="'tel://'+activity.activity.extra.service_contact">一键拨打</van-button>
              </div>
            </div>
            <div class="border-t"></div>
            <div class="p-4">
              <van-image :src="activity.activity.extra.service_qrcode.url"></van-image>
            </div>
          </div>
          <div class="-mb-8 text-white text-center text-xl" @click="showService = false">
            <van-icon name="close"/>
          </div>
        </van-popup>

      </template>

    </div>
  </Page>
</template>

<script setup>
import {nextTick, ref} from 'vue';
import {useStore} from "vuex";
import {useRoute, useRouter} from "vue-router";
import Page from "../components/Page.vue"
import {computed, onMounted, watch} from "vue";

import apis from '../apis'
import bag from '../assets/images/red-bag.png'
import invite1 from '../assets/images/invite-1.jpg'
import invite2 from '../assets/images/invite-2.jpg'
import invite3 from '../assets/images/invite-3.jpg'
import app from "../configs/app";
import {getPx} from "../utils/rem"

const store = useStore()
const router = useRouter()
const route = useRoute()

const user = computed(() => store.state.user)
const touchUser = ref(null)
const activity = ref(null)

const active = ref(0)
const showCode = ref(false)
const downtime = ref(0)

const codeUrl = ref('')
const qrcode = ref(null)

const showService = ref(false)

const couponProcess = ref(null)
const maxBonus = computed(() => {
  if (!activity.value.commision_config.coupon_bonus) {
    return 0
  }
  let bonusSettings = activity.value.commision_config.coupon_bonus_settings;
  return bonusSettings[bonusSettings.length - 1].money
})

import QRCode from "qrcode";
import dayjs from "dayjs";
import LoadingBox from "../components/LoadingBox.vue";

const spaceNumber = (num) => {
  return ((num+"").length==1 ? "0" + (num+"") : num)
}

let getRight = (right) => {
  if (!touchUser.value) {
    return right
  }
  let result = touchUser.value.rights.filter((el) => {
    return right.id == el.right_id
  })
  if(result[0]) {
    right.unlock = true
    right.code = result[0].code
  }
  return right
}

const taskTotal = computed(() => {
  let t = [...rights.value.pay, ...rights.value.assistance]
  return t.reduce((curr, el) => {
    return curr + (el.unlock_config.condition_type == 'share_buy' || el.unlock_config.condition_type == 'share') ? el.unlock_config.count : 0
  }, 0)
})

const rights = computed(() => {

  let r = {
    "pay": [], // 即刻购权益
    "assistance": [] // 分享权益
  }

  if (!activity.value)
    return r

  if (activity.value.goods.require_verify) { // 是否需要核销
    let orderRight = {
      name: activity.value.goods.name,
      cover: activity.value.goods.goods_cover,
      description: activity.value.goods.description,
      unlock_config: {"count": 0, "condition_type": "buy_once"},
      id: null, // 当前本订单权益（即核销当前订单）
      unlock: false,
      code: ''
    }
    getRight(orderRight)
    r.pay.push(orderRight)
  }

  activity.value.rights.forEach((el) => {
    if (el.unlock_config.condition_type == 'share_buy' || el.unlock_config.condition_type == 'share') {
      r.assistance.push(getRight(el))
    } else {
      r.pay.push(getRight(el))
    }
  })

  return r;
})


const onCode = (right) => {
  codeUrl.value = window.location.origin + location.pathname.substr(0, location.pathname.length-1) + (app.history=='history'?'':'/#') + '/right_write_off?code=' + right.code + '&activity_id=' + activity.value.id
  showCode.value = true

  nextTick(() => {
    new Promise((resolve, reject) => {
      QRCode.toCanvas(qrcode.value, codeUrl.value, {
        scale: 4, // default: 4
        width: 500,
      }, (error) => {
        if (error) {
          reject(error)
        } else {
          resolve()
        }
      })
    }).catch((e) => {
      console.log(e)
    })
  })
}

const onCoupon = (right) => {
  apis.right.coupon(right.id, {}).then(({data: result}) => {
    router.push({name: "coupon_detail", query: {id: result.data.id}})
  })
}


const onPoster = () => {
  router.push({name: "poster", query: {activity_id: activity.value.id}})
}

const onHome = () => {
  router.push({name: "home", query: {activity_id: activity.value.id}})
}

const onRank = () => {
  router.push({name: "cash", query: {activity_id: activity.value.id}})
}

const pageLoading = ref(true)
onMounted(async () => {
  await apis.activity.show({
    params: {
      id: route.query.activity_id,
    }
  }).then(({data: result}) => {
    activity.value = result.data
    downtime.value = dayjs(activity.value.activity.end_time).diff(new Date())
  })

  // 确定邀请关系
  if (user.value.user) {
    await apis.activity.touch({
      params: {
        id: route.query.activity_id,
        sid: route.query.sid // 保存邀请人id
      }
    }).then(({data: result}) => {
      touchUser.value = result.data
    })

    if (activity.value.commision_config.coupon_bonus) {
      await apis.activity.couponProcess({
        params: {
          activity_id: route.query.activity_id,
        }
      }).then(({data: result}) => {
         couponProcess.value = result.data
      })
    }
  }
  pageLoading.value = false
})

const onAll = () => {
  router.push({name: "share", query: {"activity_id": activity.value.id}})
}

</script>

<style scoped>
  .less-title {
    display: flex;
    align-items: center;
  }
 .less-title:before {
   display: block;
   content: '';
   width: 3rem;
   height: .1rem;
   background: linear-gradient(90deg, #ffffff 0, #fa8c16);
   margin-right: 0.56rem;
 }
  .less-title:after {
    display: block;
    content: '';
    width: 3rem;
    height: .1rem;
    background: linear-gradient(90deg, #fa8c16 0, #ffffff);
    margin-left: 0.56rem;
  }

  .qrcode{
    width: 10rem!important;
    height: 10rem!important;
  }
</style>